package com.example.leetdemo.process;

public class Solution1001 {

    public static void main(String[] args) {
        Solution1001 solution1001 = new Solution1001();
        solution1001.gridIllumination(5, new int[][] {
                {0,0}, {0,4}
        }, new int[][] {
                {0,4}, {0,1},{1,4}
        });
    }

    public int[] gridIllumination(int n, int[][] lamps, int[][] queries) {
        int[][] dp = new int[n + 2][n + 2];
        int[][] check = new int[n][n];
        int[] result = new int[queries.length];
        for (int i = 0; i < lamps.length; i++) {
            check[lamps[i][0]][lamps[i][1]] = 1;
            fillX(dp, lamps[i][0] + 1, lamps[i][1] + 1, 1);
            fillY(dp, lamps[i][0] + 1, lamps[i][1] + 1, 1);
            fillAngle(dp, lamps[i][0] + 1, lamps[i][1] + 1, 1);
            fillAntiAngle(dp, lamps[i][0] + 1, lamps[i][1] + 1, 1);
        }
        for (int i = 0; i < queries.length; i++) {
            int x = queries[i][0], y = queries[i][1];
            result[i] = dp[x + 1][y + 1] > 0 ? 1 : 0;
            for (int j = x - 1; j < x + 1; j++) {
                for (int k = y - 1; k < y + 1; k++) {
                    if (check[x][y] != 0) {
                        check[x][y] = 0;
                        fillX(dp, queries[i][0] + 1, queries[i][1] + 1, -1);
                        fillY(dp, queries[i][0] + 1, queries[i][1] + 1, -1);
                        fillAngle(dp, queries[i][0] + 1, queries[i][1] + 1, -1);
                        fillAntiAngle(dp, queries[i][0] + 1, queries[i][1] + 1, -1);
                    }
                }
            }

        }
        return result;
    }

    private void fillX(int[][] grid, int x, int y, int operate) {
        for (int i = 0; i < grid.length; i++) {
            grid[x][i] += operate;
        }
    }

    private void fillY(int[][] grid, int x, int y, int operate) {
        for (int i = 0; i < grid.length; i++) {
            grid[x][i] += operate;
        }
    }

    private void fillAngle(int[][] grid, int x, int y, int operate) {
        int temp = Math.min(x, y);
        int i = x - temp, j = y - temp;
        for (; i < grid.length - 1 && j < grid.length - 1; i++, j++) {
            grid[i][j] += operate;
        }
    }

    private void fillAntiAngle(int[][] grid, int x, int y, int operate) {
        int temp = Math.min(x, y);
        int i = x + temp, j = y - temp;
        for (; i >= 0 && j < grid.length - 1; i--, j++) {
            grid[i][j] += operate;
        }
    }

}
